﻿using SuperSocket;
using SuperSocket.ProtoBase;
using SuperSocket.Command;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace GpsServer
{
    [Command(Key = ProtocolNo.LOCATION)]
    public class LocationCommand : IAsyncCommand<MyPackageInfo>
    {
        private readonly ILogger _logger;

        public LocationCommand(ILogger<LocationCommand> logger)
        {
            _logger = logger;
        }

        public async ValueTask ExecuteAsync(IAppSession session, MyPackageInfo package)
        {
            var mySession = (MySession)session;
            if (!mySession.IsLogin) return;

            var data = package.Content;
            //时间
            var time = new DateTime(2000 + data[0], data[1], data[2], data[3], data[4], data[5]);
            //GPS
            var tmp = Convert.ToString(data[6], 16).PadLeft(2, '0');
            var gpsInfoLen = Convert.ToInt32("0x0" + tmp[0], 16);//GPS信息长度
            var satelliteCount = Convert.ToInt32("0x0" + tmp[1], 16);//卫星数量
            var latitude = BitConverter.ToInt32(data.Skip(7).Take(4).Reverse().ToArray()) / 30000D / 60;//纬度
            var longitude = BitConverter.ToInt32(data.Skip(11).Take(4).Reverse().ToArray()) / 30000D / 60;//经度
            var speed = (int)data[15];//速度
            tmp = Convert.ToString(data[16], 2).PadLeft(8, '0') + Convert.ToString(data[17], 2).PadLeft(8, '0');
            var isRealtimeGPS = tmp[2] == '1';//0:实时GPS 1:差分定位
            var isLocation = tmp[3] == '1';//是否定位
            var isWestLongitude = tmp[4] == '1';//是否西经
            var isNorthLatitude = tmp[5] == '1';//是否北纬
            tmp = "000000" + tmp.Substring(6);
            var bytes = new byte[2];
            bytes[1] = Convert.ToByte(tmp.Substring(0, 8), 2);
            bytes[0] = Convert.ToByte(tmp.Substring(8), 2);
            var direction = BitConverter.ToInt16(bytes.ToArray());//方向

            _logger.LogDebug("LOCATION: TerminalID={0} Time={1} Satellites={2} Point={3} Speed={4} IsLocation={5} Direction={6}"
                , mySession.TerminalID, time, satelliteCount, latitude + "," + longitude
                , speed, isLocation, direction);
        }
    }
}